package com.ysh.service.impl;

import com.ysh.bean.User;
import com.ysh.mapper.UserMapper;
import com.ysh.service.UserService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class UserServiceImpl implements UserService {
    @Override
    public User login(String username, String password) {
        // 定义相关参数
        InputStream is = null;
        SqlSession sqlSession = null;
        User user = null;
        try{
            // 1. 加载核心配置文件
            is = Resources.getResourceAsStream("MyBatisConfig.xml");

            // 2. 构建SqlSession工厂对象
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);

            // 3. 获取SqlSession对象
            sqlSession = sqlSessionFactory.openSession(true);

            // 4. 获取UserMapper接口实现类对象
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            // 5. 调用实现类对象的登录方法
            user = mapper.login(username, password);

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 6. 释放资源
            if (sqlSession != null){
                sqlSession.close();
            }
            if (is != null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 7. 返回结果到控制层
        return user;
    }
}
